package ar.com.photo_admin.service
import org.springframework.web.multipart.*;

import ar.com.photo_admin.domain.Event;
import ar.com.photo_admin.domain.EventAlbum;
import ar.com.photo_admin.domain.EventPhoto;
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import grails.converters.*;

import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes


class EventService extends BaseService {

	def eventPhotoService;


	def findEventById(def eventId){
		def event = Event.get(eventId);
		event = event.refresh();
		return event;
	}

	def confirmChangesEvent(def eventId){
		Event event = findEventById(eventId);		
		addNewPhotos(event);
		deleteMarkedPhotos(event);		
		event.save(flush:true);
	}
	
	def cancelChangesEvent(def eventId, def eventNumber){
		deleteTemporalPhotos(eventNumber);
		if (eventId != ""){
			Event event = findEventById(eventId);
			cancelDeletePhotos(event);
			event.save(flush:true);
		}		
	}
	
	//Elimina las fotos que se iban a agregar al evento cuando se confirme 
	def deleteTemporalPhotos(eventNumber){
		def photos = EventPhoto.findAllByTemporalEventNumber(eventNumber);
		deletePhotosCollection(photos);
	}

	//Elimina las fotos marcadas para ser eliminadas
	def deleteMarkedPhotos(event){
		def photos = EventPhoto.findAllByToBeDeletedAndEvent(true,event);		
		deletePhotosCollection(photos);
	}	
	
	def deletePhotosCollection(photos){
		photos.each(){
			
			EventPhoto photo = it
			boolean fileSuccessfullyDeleted =  new File(photo.pathInServer).delete();
			boolean thumbnailMediumSuccessfullyDeleted =  new File(photo.thumbnailMediumPathInServer).delete();
			boolean thumbnailSuccessfullyDeleted =  new File(photo.thumbnailPathInServer).delete();
			if(!fileSuccessfullyDeleted || !thumbnailSuccessfullyDeleted || !thumbnailMediumSuccessfullyDeleted){
				//TODO encapsular
				throw new RuntimeException("No se pudo borrar la foto");
			}
			
			Event photoEvent = photo.event
			
			if(photoEvent!= null)
			{
				//Remueve la foto del evento
				photoEvent.removePhoto(photo);
				
				//Se fija si esta como cover en algun evento.
				EventPhoto cover = photoEvent.coverPhoto;
				if (photo.id == cover.id){
					photoEvent.coverPhoto = null;
				}
				
				//Se fija si debe borrarlo de algun album				
				Iterator iter = photo.getAlbums().iterator();
				while (iter.hasNext()) {
					photo.removeFromAlbums(iter.next())
				}	
				
				//Se fija si debe borrarlo del cover de algun evento
				def coverOfAlbums = EventAlbum.findAllByCoverPhoto(photo)
				coverOfAlbums.each {					
					it.coverPhoto = null;
				}			
					
			}									
				
			photo.delete(flush:true);
		}
	}
	
	def cancelDeletePhotos(event){
		def photos = EventPhoto.findAllByToBeDeletedAndEvent(true,event);
		photos.each(){
			it.toBeDeleted = false;
		}
	}
		
	def addNewPhotos(event){
		def photos = EventPhoto.findAllByTemporalEventNumber(event.number);		
		photos.each(){
			it.temporalEventNumber = 0;
			event.addToPhotos(it)
		}
	}
	
	
	
	def getEventConfirmedAndNotConfirmedPhotosAsJSON(eventId,eventNumber){
		def photos = [];
		if (eventId != "")
			photos.addAll(getEventPhotos(eventId));
		photos.addAll(EventPhoto.findAllByTemporalEventNumber(eventNumber));		
		return convertPhotosToJSON(photos);
	}
	

	def getEventPhotos(eventId){
		Event event = findEventById(eventId);
		return event.photos;
	}

	def getEventPhotosAsJSON(eventId){
		def photos = getEventPhotos(eventId);
		return convertPhotosToJSON(photos) ; 
	}
	
	def convertPhotosToJSON(photos){
		Collection results = [];
		def result;
		for (EventPhoto photo : photos){
			result = [:];
			result['name'] = photo.name
			result['url'] = photo.url
			result['photoId'] = photo.id;
			result['thumbnailUrl'] = photo.thumbnailUrl;
			result['thumbnailMediumUrl'] = photo.thumbnailMediumUrl;
			results << result
		}
		return results as JSON;
	}

	def deletePhotoTemporally(eventId,photoId){		
		EventPhoto photo = eventPhotoService.findEventPhotoById(photoId);
		photo.toBeDeleted = true
		photo.save(flush:true);
	
	}

	
	
	
}
